package com.wangyh.edit.prettyedit.tree;

import com.wangyh.edit.prettyedit.constant.EditConstant;
import com.wangyh.edit.prettyedit.mainframe.MainFrameView;
import com.wangyh.edit.prettyedit.util.FileImgUtils;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;

import java.io.File;
import java.io.IOException;

/**
 * 文件夹右键菜单
 */
public class MenuContextFolder {

    /**
     * 构造文件弹出菜单
     *
     * @param tree
     * @param mainFrameView
     */
    public static void generateFileMenu(TreeView<File> tree, ContextMenu addMenu, MainFrameView mainFrameView){
        MenuItem addFolderMenuItem = new MenuItem("新增文件夹");
        MenuItem addTxtMenuItem = new MenuItem("新增text文档");
        MenuItem addHtmlMenuItem = new MenuItem("新增html文档");
        MenuItem addMdMenuItem = new MenuItem("新增markdown文档");
        MenuItem addFlowMenuItem = new MenuItem("新增流程图");

        //临时禁用
        addMdMenuItem.setDisable(true);
        addFlowMenuItem.setDisable(true);

        //分割线
        SeparatorMenuItem separator = new SeparatorMenuItem();
        MenuItem deleMenuItem = new MenuItem("删除目录");
        MenuItem openDiskMenuItem = new MenuItem("打开文件路径");
        MenuItem reloadMenuItem = new MenuItem("刷新目录");

        addFolderMenuItem.getStyleClass().add("zkh_MenuItem");
        addMdMenuItem.getStyleClass().add("zkh_MenuItem");
        addHtmlMenuItem.getStyleClass().add("zkh_MenuItem");
        addFlowMenuItem.getStyleClass().add("zkh_MenuItem");
        deleMenuItem.getStyleClass().add("zkh_MenuItem");
        reloadMenuItem.getStyleClass().add("zkh_MenuItem");
        openDiskMenuItem.getStyleClass().add("zkh_MenuItem");
        addTxtMenuItem.getStyleClass().add("zkh_MenuItem");

        addMenu.getItems().addAll(addFolderMenuItem,addTxtMenuItem,addHtmlMenuItem,addMdMenuItem,
                addFlowMenuItem,separator,deleMenuItem,openDiskMenuItem,reloadMenuItem);

        //新增文件夹
        addFolderMenuItem.setOnAction((ActionEvent t) -> {
            TreeItem<File> selectItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
            String path = selectItem.getValue().getAbsolutePath();

            //如果没有，则创建目录
            File f = createFolderNode(path);

//            selectItem.getChildren().add(newFileNode);
//            selectItem.setExpanded(true);

            //更新父亲
            selectItem.getChildren().clear();
            for(final File file: selectItem.getValue().listFiles()){
                if(file.isDirectory()){
                    //图标
                    ImageView folderIcon = new ImageView(
                            new Image(MainFrameView.class.getResourceAsStream("/img/folder.png"))
                    );
                    folderIcon.setFitHeight(EditConstant.treeIconHeight);
                    folderIcon.setFitWidth(EditConstant.treeIconWeight);
                    selectItem.getChildren().add(new FileTreeItem(file,folderIcon));
                }else{
                    //设置图标
                    ImageView fileIcon = FileImgUtils.getFileImageView(file);
                    selectItem.getChildren().add(new FileTreeItem(file,fileIcon));
                }
            }

//            TreeItem<File> newFileNode = new FileTreeItem(f,folderIcon);
//            tree.requestFocus();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    ObservableList<TreeItem<File>> children = selectItem.getChildren();
                    for(int i=0; i<children.size(); i++){
                        TreeItem<File> fileTreeItem = children.get(i);
                        if(fileTreeItem.getValue().getAbsolutePath().equals(f.getAbsolutePath())){
                            tree.edit(fileTreeItem);
                            tree.getSelectionModel().select(fileTreeItem);
                            break;
                        }
                    }
                }
            });
        });

        //新增txt文件
        addTxtMenuItem.setOnAction((ActionEvent t) -> {
            TreeItem<File> selectItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
            String path = selectItem.getValue().getAbsolutePath();

            //如果没有，则创建目录
            File f = createTxtNode(path);

            //更新父亲
            selectItem.getChildren().clear();
            for(final File file: selectItem.getValue().listFiles()){
                if(file.isDirectory()){
                    //图标
                    ImageView folderIcon = new ImageView(
                            new Image(MainFrameView.class.getResourceAsStream("/img/folder.png"))
                    );
                    folderIcon.setFitHeight(EditConstant.treeIconHeight);
                    folderIcon.setFitWidth(EditConstant.treeIconWeight);
                    selectItem.getChildren().add(new FileTreeItem(file,folderIcon));
                }else{
                    //设置图标
                    ImageView fileIcon = FileImgUtils.getFileImageView(file);
                    selectItem.getChildren().add(new FileTreeItem(file,fileIcon));
                }
            }

//            selectItem.setExpanded(true);

//            tree.requestFocus();
//            tree.getSelectionModel().select(newFileNode);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    ObservableList<TreeItem<File>> children = selectItem.getChildren();
                    for(int i=0; i<children.size(); i++){
                        TreeItem<File> fileTreeItem = children.get(i);
                        if(fileTreeItem.getValue().getAbsolutePath().equals(f.getAbsolutePath())){
                            tree.edit(fileTreeItem);
                            tree.getSelectionModel().select(fileTreeItem);
                            break;
                        }
                    }
                }
            });
        });

        //新增html文件
        addHtmlMenuItem.setOnAction((ActionEvent t) -> {
            TreeItem<File> selectItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
            String path = selectItem.getValue().getAbsolutePath();

            //如果没有，则创建目录
            File f = createHtmlNode(path);

            //更新父亲
            selectItem.getChildren().clear();
            for(final File file: selectItem.getValue().listFiles()){
                if(file.isDirectory()){
                    //图标
                    ImageView folderIcon = new ImageView(
                            new Image(MainFrameView.class.getResourceAsStream("/img/folder.png"))
                    );
                    folderIcon.setFitHeight(EditConstant.treeIconHeight);
                    folderIcon.setFitWidth(EditConstant.treeIconWeight);
                    selectItem.getChildren().add(new FileTreeItem(file,folderIcon));
                }else{
                    //设置图标
                    ImageView fileIcon = FileImgUtils.getFileImageView(file);
                    selectItem.getChildren().add(new FileTreeItem(file,fileIcon));
                }
            }

//            selectItem.setExpanded(true);

//            tree.requestFocus();
//            tree.getSelectionModel().select(newFileNode);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    ObservableList<TreeItem<File>> children = selectItem.getChildren();
                    for(int i=0; i<children.size(); i++){
                        TreeItem<File> fileTreeItem = children.get(i);
                        if(fileTreeItem.getValue().getAbsolutePath().equals(f.getAbsolutePath())){
                            tree.edit(fileTreeItem);
                            tree.getSelectionModel().select(fileTreeItem);
                            break;
                        }
                    }
                }
            });
        });

        //新增md文件
        addMdMenuItem.setOnAction((ActionEvent t) -> {
            TreeItem<File> selectItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
            String path = selectItem.getValue().getAbsolutePath();

            //如果没有，则创建目录
            File f = createMdNode(path);

            //更新父亲
            selectItem.getChildren().clear();
            for(final File file: selectItem.getValue().listFiles()){
                if(file.isDirectory()){
                    //图标
                    ImageView folderIcon = new ImageView(
                            new Image(MainFrameView.class.getResourceAsStream("/img/folder.png"))
                    );
                    folderIcon.setFitHeight(EditConstant.treeIconHeight);
                    folderIcon.setFitWidth(EditConstant.treeIconWeight);
                    selectItem.getChildren().add(new FileTreeItem(file,folderIcon));
                }else{
                    //设置图标
                    ImageView fileIcon = FileImgUtils.getFileImageView(file);
                    selectItem.getChildren().add(new FileTreeItem(file,fileIcon));
                }
            }
//            selectItem.setExpanded(true);

//            tree.requestFocus();
//            tree.getSelectionModel().select(newFileNode);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    ObservableList<TreeItem<File>> children = selectItem.getChildren();
                    for(int i=0; i<children.size(); i++){
                        TreeItem<File> fileTreeItem = children.get(i);
                        if(fileTreeItem.getValue().getAbsolutePath().equals(f.getAbsolutePath())){
                            tree.edit(fileTreeItem);
                            tree.getSelectionModel().select(fileTreeItem);
                            break;
                        }
                    }
                }
            });
        });

        //新增flow文件
        addFlowMenuItem.setOnAction((ActionEvent t) -> {
            TreeItem<File> selectItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
            String path = selectItem.getValue().getAbsolutePath();

            //如果没有，则创建目录
            File f = createFileNode(path,6);

            //更新父亲
            selectItem.getChildren().clear();
            for(final File file: selectItem.getValue().listFiles()){
                if(file.isDirectory()){
                    //图标
                    ImageView folderIcon = new ImageView(
                            new Image(MainFrameView.class.getResourceAsStream("/img/folder.png"))
                    );
                    folderIcon.setFitHeight(EditConstant.treeIconHeight);
                    folderIcon.setFitWidth(EditConstant.treeIconWeight);
                    selectItem.getChildren().add(new FileTreeItem(file,folderIcon));
                }else{
                    //设置图标
                    ImageView fileIcon = FileImgUtils.getFileImageView(file);
                    selectItem.getChildren().add(new FileTreeItem(file,fileIcon));
                }
            }

//            selectItem.setExpanded(true);

//            tree.requestFocus();
//            tree.getSelectionModel().select(newFileNode);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    ObservableList<TreeItem<File>> children = selectItem.getChildren();
                    for(int i=0; i<children.size(); i++){
                        TreeItem<File> fileTreeItem = children.get(i);
                        if(fileTreeItem.getValue().getAbsolutePath().equals(f.getAbsolutePath())){
                            tree.edit(fileTreeItem);
                            tree.getSelectionModel().select(fileTreeItem);
                            break;
                        }
                    }
                }
            });
        });

        //删除文件夹
        deleMenuItem.setOnAction((ActionEvent t) -> {
            TreeItem<File> selectItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
            String path = selectItem.getValue().getAbsolutePath();

            //判断是否存在
            File f = new File(path);
            if(!f.exists()){
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText(null);
                alert.setTitle("提示！");
                alert.setHeaderText("当前结点不存在！");
                alert.show();
                return;
            }
            if(!f.isDirectory()){
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText(null);
                alert.setTitle("提示！");
                alert.setHeaderText("当前结点不是文件夹");
                alert.show();
                return;
            }
            if(f.listFiles().length>0){
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText(null);
                alert.setTitle("提示！");
                alert.setHeaderText("当前结点下有文件，请先删除下级文件");
                alert.show();
                return;
            }

            //删除文件夹
            f.delete();

            tree.requestFocus();
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    boolean remove = selectItem.getParent().getChildren().remove(selectItem);
                    System.out.println("Remove");
                }
            });
        });

        //我的电脑打开
        openDiskMenuItem.setOnAction((ActionEvent t) -> {
            TreeItem<File> selectItem = (TreeItem) tree.getSelectionModel().getSelectedItem();
            String path = selectItem.getValue().getAbsolutePath();

            try {
                Runtime.getRuntime().exec("EXPLORER.EXE /e,/root," + path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        //重新加载
        reloadMenuItem.setOnAction((ActionEvent t) -> {
////            tree.refresh();
//            BorderPane borderPane = (BorderPane) tree.getScene().getRoot();
//            //左侧树
//            LeftTreeView leftTreeView = new LeftTreeView();
//            TreeView newTree = leftTreeView.getTree();
//            borderPane.setLeft(newTree);

            ((TreeItem)tree.getSelectionModel().getSelectedItem()).getChildren().clear();
            //更新儿子
            for(final File sonfile: ((TreeItem<File>)tree.getSelectionModel().getSelectedItem()).getValue().listFiles()){
                if(sonfile.isDirectory()){
                    ImageView folderIcon = new ImageView(
                            new Image(MainFrameView.class.getResourceAsStream("/img/folder.png"))
                    );
                    folderIcon.setFitHeight(EditConstant.treeIconHeight);
                    folderIcon.setFitWidth(EditConstant.treeIconWeight);
                    tree.getSelectionModel().getSelectedItem().getChildren().add(new FileTreeItem(sonfile,folderIcon));
                }else{
                    //设置图标
                    ImageView fileIcon = FileImgUtils.getFileImageView(sonfile);
                    tree.getSelectionModel().getSelectedItem().getChildren().add(new FileTreeItem(sonfile,fileIcon));
                }
            }
            //复制完，该节点需要展开。
            tree.getSelectionModel().getSelectedItem().setExpanded(true);
        });
    }

    private static File createFolderNode(String path){
        File f = new File(path + File.separator + "新增目录");
        if(!f.exists()){
            f.mkdirs();
            return f;
        }else{
            for(int i=1; i<100; i++){
                f = new File(path + File.separator + "新增目录" + i);
                if(!f.exists()){
                    f.mkdirs();
                    return f;
                }
            }
        }

        return null;
    }

    private static File createTxtNode(String path){
        long time = System.currentTimeMillis();
        File f = new File(path + File.separator + "新建txt" + time + ".txt");
        try {
            f.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return f;
    }


    private static File createHtmlNode(String path){
        long time = System.currentTimeMillis();
        File f = new File(path + File.separator + "新建html" + time + ".html");
        try {
            f.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return f;
    }


    private static File createFileNode(String path,int type){
        long time = System.currentTimeMillis();
        String fileType = "txt";
        if(type==4){
            fileType = "json";
        }else if(type==5){
            fileType = "xml";
        }else if(type==6){
            fileType = "flow";
        }
        File f = new File(path + File.separator + "新建" + fileType + time + "." + fileType);
        try {
            f.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return f;
    }


    private static File createMdNode(String path){
        long time = System.currentTimeMillis();
        File f = new File(path + File.separator + "新建markdown" + time + ".md");
        try {
            f.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return f;
    }
}
